import { Controller } from 'egg';
import { CommonUtil } from '../../utils';

export default class LoginController extends Controller {
  // 用户注册
  private access_token_expires_time = 14 * 24 * 60 * 60;
  private refresh_token_expires_time = 2 * 60 * 60;
  public async register() {
    const { ctx } = this;
    const { body: { username, password } } = ctx.request;
    const registerRule = {
      username: { type: 'string', max: 16, min: 6 },
      password: { type: 'string', max: 16, min: 6, format: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/ },
    };
    try {
      ctx.validate(registerRule);
      const userInfo = await ctx.model.User.findOne({ where: { username } });
      if (userInfo) {
        ctx.body = {
          err_msg: '该用户名已被注册',
        };
      } else {
        const salt = CommonUtil.createRandomString();
        const newuser = await ctx.model.User.create({ username, password: CommonUtil.createMD5(password, salt), salt });
        ctx.body = {
          uid: newuser.id,
          username: newuser.username,
        };
      }
    } catch (e) {
      ctx.body = {
        err_msg: '用户名或密码不符合规则',
      };
    }
  }
  public async refreshToken() {
    const { ctx } = this;
    const { body: { uid, access_token: outerAccessToken } } = ctx.request;
    const userInfo = await ctx.model.User.findOne({ where: { id: uid } });
    if (userInfo) {
      const access_token = await ctx.app.redis.get(`${uid}_access_token`) as string;
      if (access_token && access_token === outerAccessToken) {
        const refresh_token = CommonUtil.createRandomString({ length: 36 });
        await ctx.app.redis.set(`${userInfo.id}_refresh_token`, refresh_token, 'ex', 1 * 60);
        const token = ctx.app.jwt.sign({ uid: userInfo.id, access_token, refresh_token }, ctx.app.config.jwt.secret);
        ctx.body = {
          // expires: new Date().valueOf() + 2,
          username: userInfo.username,
          token,
        };
      } else {
        ctx.body = {
          err_msg: 'access_token过期',
        };
      }
    } else {
      ctx.body = {
        err_msg: '无该用户',
      };
    }
  }
  public async login() {
    const { ctx } = this;
    const { body: { username, password } } = ctx.request;
    const registerRule = {
      username: { type: 'string', max: 16, min: 6 },
      password: { type: 'string', max: 16, min: 6, format: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/ },
    };
    try {
      ctx.validate(registerRule);
      const userInfo = await ctx.model.User.findOne({ where: { username } });
      if (userInfo) {
        const checkPassword = CommonUtil.createMD5(password, userInfo.salt);
        if (checkPassword === userInfo.password) {
          let access_token = await ctx.app.redis.get(`${userInfo.id}_access_token`) as string;
          let refresh_token = await ctx.app.redis.get(`${userInfo.id}_refresh_token`) as string;
          if (!access_token || !refresh_token) {
            access_token = CommonUtil.createRandomString({ length: 36 });
            refresh_token = CommonUtil.createRandomString({ length: 36 });
            await ctx.app.redis.set(`${userInfo.id}_refresh_token`, refresh_token, 'ex', this.refresh_token_expires_time);
            await ctx.app.redis.set(`${userInfo.id}_access_token`, access_token, 'ex', this.access_token_expires_time);
          }
          const token = ctx.app.jwt.sign({ uid: userInfo.id, access_token, refresh_token }, ctx.app.config.jwt.secret);
          ctx.body = {
            // expires: new Date().valueOf() + 2,
            access_token,
            username: userInfo.username,
            createtime: userInfo.createdAt,
            token,
          };
        } else {
          ctx.body = {
            err_msg: '密码不正确',
          };
        }
      } else {
        ctx.body = {
          err_msg: '用户名不正确',
        };
      }
    } catch (e) {
      ctx.body = {
        err_msg: '用户名或密码不符合规则',
      };
    }
  }
}
